package com.demo.zlb.sso.login.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.demo.zlb.sso.login.constants.Constants.TOKEN_SESSION_KEY;
import static com.demo.zlb.sso.login.constants.Constants.USER_INFO_KEY;

/**
 * @author jie.chen
 * @date 2022-03-30 15:14
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 登录
     *
     * @param ticketId
     * @param request
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("ticketId") String ticketId, HttpServletRequest request) {
        HttpSession session = request.getSession();
        //1. 通过ticketId 换取 accessToken
        String token = authService.getTokenByTicketId(ticketId);
        //2. 保存accessToken
        session.setAttribute(TOKEN_SESSION_KEY, token);
        //3. 通过accessToken 获取用户信息
        JSONObject userInfo = authService.getUserInfoByToken(token);
        //4. 缓存用户信息
        session.setAttribute(USER_INFO_KEY, userInfo);
        //5. 生成登录态
        //demo示例用session做登录态，故忽略这一步
        return "success";
    }


    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @PostMapping("/userInfo")
    public JSONObject userInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(USER_INFO_KEY);
        if (attribute != null) {
            return (JSONObject) attribute;

        } else {
            throw new RuntimeException("未登录");
        }
    }

}
